package com.ting.test.util;


import com.ting.test.CommonConstant;

import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.locks.ReentrantLock;

/**
 *
 * @author 雷霆
 * @version 1.0.0
 * @date$ 2018/1/20
 *
 * Description： 取号器工具类
 *
 * Modification History:
 *
 */
public class ConcurrentLinkedQueueUtil {

    /**
     * 请求号队列
     */
    private  static final ConcurrentLinkedQueue<String> queue =new ConcurrentLinkedQueue<String>();

    /**
     * 并发锁
     */
    private  static final ReentrantLock mainLock = new ReentrantLock();

    /**
     * 初始化请求取号器
     */
    static {
        init();
    }

    /**
     * 获取一个请求号，同时从队列中移除该请求号，如果队列为空，返回null
     * @return
     */
    public static String getReqNo(){
        ReentrantLock lock=mainLock;

        try {
            lock.lock();
            return queue.poll();
        }finally {
            lock.unlock();
        }
    }

    /**
     *向队列尾部插入 一条记录，如果插入失败，返回false,成功返回true
     * @param reqNo
     * @return
     */
    public static boolean setReqNo(String reqNo){
            return queue.offer(reqNo);
    }

    /**
     * 初始化取号器
     */
    public static void init(){
        ReentrantLock lock=mainLock;
        try {
            lock.lock();
            for(int i = 1; i <= CommonConstant.MAX_REQUEST_NUM; i++){
                queue.offer(String.valueOf(i));
            }
        }finally {
            lock.unlock();
        }

    }
}
